#!/usr/bin/python
import MuConnection, MuNetworkConfiguration, MuTestApi, MuRestApi, time, sys 


class verify():

	USERNAME = 'admin'
	PASSWORD = ''
	MU = ''
	myMuConnection = None
	results = []
	error = True
	passCount = 0
	failCount = 0
	count = 0

	def __init__(self,mu,username,password,scenarioUuid,csvUUID,csvData,csvName,hostList,debugFailed=False,verbose=False):
		""" set up the Test """
		self.USERNAME = username
		self.PASSWORD = password
		self.MU = mu
		#print "-------"," ",mu," ",username," ",password
		
		myMuConnection = MuConnection.MuConnection(self.MU,self.USERNAME,self.PASSWORD)
		self.myMuConnection = myMuConnection
		myTestApi = MuTestApi.MuTestApi(myMuConnection)
		myTestApi.VERBOSE = verbose
		myMuConnection.VERBOSE = verbose
		myTestApi.newSession()
		myTestApi.loadScenario(scenarioUuid)
		response = myTestApi.getHosts()
		hosts = response.RETRIEVED_OBJECT
		#response = myTestApi.getOptions()
		#print response
		hostCount=0
		#myTestApi.VERBOSE = True
		for host in hosts:
			respone = myTestApi.setHost(host["role"],hostList[hostCount])
			if not response.isCompleted() or response.hasError():
				print "ERROR BINDING HOSTS"
				print response.getRawResponse()
				result = myTestApi.Result(None)
				result.status = 'ERROR BINDING HOSTS'
				result.testName = csvName
				result.testResult = 'ERROR'
				results = [result]
				return
			#else:
			#	print "bound host "+ hostList[hostCount]+ " for role "+host["role"]
			hostCount = hostCount + 1
		myTestApi.setupTest()
		response = myTestApi.verifyScenario()
		if response.getStatus()=="Failed" or response.hasError():
			print "TODO: Could not verify scenario"
			print "hosts: ", hosts
			print response.getRawResponse()
			result = myTestApi.Result(None)
			result.status = 'ERROR: SCENARIO VERIFY FAILED'
			result.testName = csvName
			result.testResult = 'ERROR'
			results = [result]
			myTestApi.closeSession()
			return
		if csvUUID==None and not csvData==None:
			response = myTestApi.importCSVData(csvData,csvName)
			if response.isCompleted() and not response.hasError() and response.getStatus():
				newUUID = response.getMessage()
				run = True
		elif not csvUUID==None:
			newUUID=csvUUID
			run = True
		else:
			print "error"
			run = False
		#myTestApi.VERBOSE = True
		if run:
			response = myTestApi.runTestSuite(newUUID)
			if response.isCompleted() and not response.hasError() and response.getStatus():
				#print response.getStatus()
				time.sleep(1)
				loop = True
				while loop:
					response = myTestApi.getTestSuiteStatus()
					if response.getMessage() == "Done":
						loop = False
					time.sleep(1)
				response = myTestApi.getTestSuiteResults()
				if response.isCompleted() and not response.hasError():
					resultsList = response.getRetrievedObject()
					self.results = resultsList
					for result in resultsList:
						if result.getTestResult()=="PASSED":
							self.passCount = self.passCount+1
						if result.getTestResult()=="FAILED":
							self.failCount = self.failCount+1
						if not result.getTestResult()=="END":
							self.count = self.count+1
				else:
					print "could not pull results"
			else:
				print "could not run test"
		myTestApi.VERBOSE = False
		print "PASS="+str(self.passCount)+" / FAIL="+str(self.failCount)+" / TOTAL="+str(self.count)
		myTestApi.closeSession()
		
	def getResultHeaders(self):
		#print "get headers"
		for result in self.results:
			#print "get headers return 1"
			return result.getAsCsv(True)
		#print "get headers return 2"
		return ""
	
	
	def resultsToCsv(self,includeHeaders=False):
		returnData = ""
		header = includeHeaders
		for result in self.results:
			if header:
				returnData = returnData + result.getAsCsv(True)
			returnData = returnData + result.getAsCsv()
			header = False
		return returnData
		
	def resultsToCsvFile(self, output,includeHeaders=False):
		# Open the local file for writing
		newFile = open(output, "wt")
		header = includeHeaders
		for result in self.results:
			if header:
				newFile.write(result.getAsCsv(True))
			newFile.write(result.getAsCsv())
			header = False
		newFile.close()

	
